// 通知历史页面逻辑
const app = getApp();

Page({
  data: {
    // 列表数据
    notifications: [],
    totalCount: 0,
    successCount: 0,
    todayCount: 0,
    
    // 分页控制
    page: 1,
    size: 20,
    hasMore: true,
    loading: false,
    refreshing: false,
    
    // 筛选条件
    currentFilter: 'all',
    filters: {
      all: '全部',
      success: '成功',
      failed: '失败',
      capsule: '记忆胶囊',
      mood: '心情记录',
      period: '生理期'
    },
    
    // 弹窗控制
    showFilter: false,
    showDetailPopup: false,
    selectedNotification: null,
    
    // 类型映射
    typeMap: {
      'capsule_created': { name: '胶囊创建', icon: 'gift-o', color: '#FF6B6B' },
      'capsule_opened': { name: '胶囊开启', icon: 'clock-o', color: '#4ECDC4' },
      'mood_recorded': { name: '心情记录', icon: 'smile-o', color: '#45B7D1' },
      'thief_activated': { name: '心情小偷', icon: 'fire-o', color: '#FF4757' },
      'thief_recovered': { name: '追回成功', icon: 'shield-o', color: '#2ED573' },
      'period_reminder': { name: '生理期提醒', icon: 'flower-o', color: '#FF6B9D' },
      'period_started': { name: '生理期开始', icon: 'heart-o', color: '#C44569' },
      'daily_summary': { name: '每日总结', icon: 'chart-o', color: '#3742FA' },
      'weekly_report': { name: '每周报告', icon: 'bar-chart-o', color: '#5352ED' },
      'achievement_unlocked': { name: '成就解锁', icon: 'medal-o', color: '#FFD93D' },
      'special_moment': { name: '特殊时刻', icon: 'star-o', color: '#FF9FF3' },
      'emotion_sync': { name: '情感同步', icon: 'sync', color: '#A55EEA' }
    }
  },

  // 生命周期函数
  onLoad(options) {
    this.loadNotificationHistory();
    this.loadNotificationStats();
  },

  // 加载通知历史
  async loadNotificationHistory(reset = false) {
    if (this.data.loading) return;
    
    try {
      this.setData({ loading: !reset });
      
      const page = reset ? 1 : this.data.page;
      
      const res = await app.request({
        url: '/api/wechat/notification/history',
        method: 'GET',
        data: {
          page,
          size: this.data.size,
          type: this.data.currentFilter === 'all' ? '' : this.data.currentFilter,
          status: this.getStatusFilter()
        }
      });
      
      if (res.code === 200) {
        const newNotifications = res.data.content || [];
        const notifications = reset ? newNotifications : [...this.data.notifications, ...newNotifications];
        
        this.setData({
          notifications,
          hasMore: notifications.length < res.data.total,
          page: reset ? 2 : this.data.page + 1
        });
      }
    } catch (error) {
      console.error('加载通知历史失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({
        loading: false,
        refreshing: false
      });
    }
  },

  // 加载通知统计
  async loadNotificationStats() {
    try {
      const res = await app.request({
        url: '/api/wechat/notification/stats',
        method: 'GET'
      });
      
      if (res.code === 200) {
        this.setData({
          totalCount: res.data.totalCount,
          successCount: res.data.successCount,
          todayCount: res.data.todayCount
        });
      }
    } catch (error) {
      console.error('加载通知统计失败:', error);
    }
  },

  // 获取状态筛选条件
  getStatusFilter() {
    const statusMap = {
      'success': 'SUCCESS',
      'failed': 'FAILED'
    };
    return statusMap[this.data.currentFilter] || '';
  },

  // 下拉刷新
  async onRefresh() {
    this.setData({ refreshing: true });
    await this.loadNotificationHistory(true);
    await this.loadNotificationStats();
  },

  // 加载更多
  async onLoadMore() {
    if (!this.data.hasMore || this.data.loading) return;
    await this.loadNotificationHistory();
  },

  // 筛选变更
  async onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter;
    
    if (filter === this.data.currentFilter) return;
    
    this.setData({
      currentFilter: filter,
      page: 1,
      hasMore: true,
      notifications: []
    });
    
    await this.loadNotificationHistory(true);
  },

  // 显示筛选
  onShowFilter() {
    this.setData({ showFilter: !this.data.showFilter });
  },

  // 获取类型图标
  getTypeIcon(type) {
    return this.data.typeMap[type]?.icon || 'bell-o';
  },

  // 获取类型颜色
  getTypeColor(type) {
    return this.data.typeMap[type]?.color || '#666';
  },

  // 获取类型名称
  getTypeName(type) {
    return this.data.typeMap[type]?.name || type;
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'SUCCESS': '成功',
      'FAILED': '失败',
      'PENDING': '待发送',
      'SENDING': '发送中'
    };
    return statusMap[status] || status;
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    // 今天
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    }
    
    // 昨天
    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    }
    
    // 本周
    if (diff < 7 * 24 * 60 * 60 * 1000) {
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    }
    
    // 更早
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  },

  // 格式化完整时间
  formatFullTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  },

  // 通知点击
  onNotificationClick(e) {
    const notification = e.currentTarget.dataset.item;
    this.setData({
      selectedNotification: notification,
      showDetailPopup: true
    });
  },

  // 查看详情
  onViewDetail(e) {
    const notification = e.currentTarget.dataset.item;
    this.setData({
      selectedNotification: notification,
      showDetailPopup: true
    });
  },

  // 关闭详情弹窗
  onCloseDetail() {
    this.setData({
      showDetailPopup: false,
      selectedNotification: null
    });
  },

  // 重试通知
  async onRetryNotification(e) {
    const id = e.currentTarget.dataset.id;
    
    try {
      wx.showLoading({ title: '重试中...' });
      
      const res = await app.request({
        url: `/api/wechat/notification/${id}/retry`,
        method: 'POST'
      });
      
      if (res.code === 200) {
        wx.showToast({
          title: '重试已提交',
          icon: 'success'
        });
        
        // 刷新列表
        await this.loadNotificationHistory(true);
      } else {
        wx.showModal({
          title: '重试失败',
          content: res.message || '请稍后重试',
          showCancel: false
        });
      }
    } catch (error) {
      console.error('重试通知失败:', error);
      wx.showToast({
        title: '重试失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 重试选中的通知
  async onRetrySelected() {
    if (!this.data.selectedNotification) return;
    
    await this.onRetryNotification({
      currentTarget: {
        dataset: { id: this.data.selectedNotification.id }
      }
    });
    
    this.onCloseDetail();
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '我的通知历史',
      path: '/pages/notification/history',
      imageUrl: '/images/notification-history-share.jpg'
    };
  }
});